package top.dark.topic;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * Author: Darkn
 * description:
 * Create Time: 2021/5/1 8:03
 */
public class JmsConsumer {
    private static final String ACTIVEMQ_URL = "tcp://192.168.136.181:61616";
    private static final String ACTIVEMQ_TOPIC01 = "topic01";
    public static void main(String[] args) throws JMSException, IOException {
        System.out.println(" ********************消费者2号");
        // 1、获得一个Activemq连接工厂,按照给定的URL，采用默认的用户名密码
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        // 2、通过连接工厂,获得connection并启动访问
        Connection connection = factory.createConnection();
        connection.start();
        // 3、创建会话session 两个参数 boolean transacted=事务, int acknowledgeMode=确认模式（签收）
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // 4、创建目的地(具体是队列queue还是主题topic)
        Topic topic = session.createTopic(ACTIVEMQ_TOPIC01);
        // 5、创建消息的消费者，指定消费哪一个队列里面的消息
        MessageConsumer consumer = session.createConsumer(topic);
        // 6、通过监听的方式消费消息
        consumer.setMessageListener(message -> {
            if (message != null && message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                try {
                    System.out.println("****消费者接收到的消息:  " + textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        //保证控制台不关闭,阻止程序关闭
        System.in.read();

        // 7、关闭资源
        consumer.close();
        session.close();
        connection.close();
    }
}
